//
//  MainViewController.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/23.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
        
        let tb = MainTabBar()
        setValue(tb, forKey: "tabBar")
       
        tb.compoesButton.addTarget(self, action: "compoesBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    func compoesBtnClick(){
        let nav = UINavigationController(rootViewController: ComposeViewController())
        presentViewController(nav, animated: true, completion: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    private func addChildViewControllers(){
        let path = NSBundle.mainBundle().pathForResource("MainVCSetting", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        do {
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            for dict in array as![[String:String]]{
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
        }catch{
            print(error)
            addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
            addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
            addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover")
            addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
        }
    }

    private func addChildViewController(vcName:String ,title:String,imageName:String) {
            let projectName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
            let className:AnyClass = NSClassFromString(projectName + "." + vcName)!
            let vc = className.new() as! UIViewController
        
            vc.title = title
            vc.tabBarItem.image = UIImage(named: imageName)
            vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
            
            let nav = UINavigationController(rootViewController: vc)
            
            addChildViewController(nav)
    }

}
